package com.anysoft.me.ui.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.anysoft.utils.MentorLogger;
import com.blankj.utilcode.util.ToastUtils;
import com.anysoft.HostConstant;
import com.anysoft.R;
import com.anysoft.base.BaseActivity;
import com.anysoft.bean.AttentionsCommandBean;
import com.anysoft.bean.QueryAttentionByFundcodeBean;
import com.anysoft.me.utils.PermissionManager;
import com.anysoft.utils.ActivityUtils;
import com.anysoft.utils.CommonUtil;
import com.anysoft.utils.DiskUtils;
import com.anysoft.utils.FileUtils;
import com.anysoft.utils.HttpUtils;
import com.anysoft.utils.PreferencesUtils;
import com.anysoft.utils.StatusBarUtils;
import com.anysoft.utils.StringUtils;
import com.anysoft.view.BrowserLayout;
import com.anysoft.view.CustomMarqueeTextView;
import com.anysoft.view.HProgressBarLoading;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.FileCallback;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.orhanobut.logger.Logger;
import com.tencent.smtt.sdk.TbsReaderView;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import ren.yale.android.cachewebviewlib.CacheWebView;

/**
 * Created by lty on 2018/1/12.
 */

public class SupperFileActivity extends BaseActivity implements TbsReaderView.ReaderCallback, PermissionManager.OnPermissionListener {

    @BindView(R.id.leftButton)
    Button leftButton;
    @BindView(R.id.rightButton)
    ImageView rightButton;
    @BindView(R.id.cmtv_title)
    CustomMarqueeTextView cmtv_title;
    @BindView(R.id.sub_title)
    TextView subTitle;
    @BindView(R.id.shareButton)
    ImageView shareButton;
    @BindView(R.id.tv_item_web_error)
    TextView tvItemWebError;
    @BindView(R.id.ll_item_web_error)
    LinearLayout ll_item_web_error;
    @BindView(R.id.top_progress)
    HProgressBarLoading top_progress;

    private String TAG = "pdf";
    private String pdfUrl, fundName, fundCode, fundType;
    private String fileName;
    private HashMap<String, String> urlParam;
    public boolean isFollow = false;
    private Unbinder unbinder;
    private TbsReaderView mTbsReaderView;
    private RelativeLayout rl_file_container;
    private OkGo instance;
    private String fileExtension;
    private CacheWebView mWebView;
    private BrowserLayout browserLayout;
    private boolean isLoadError;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pdf_layout);
        StatusBarUtils.setWindowStatusBarColor(this, R.color.fund_title);
        unbinder = ButterKnife.bind(this);
        rl_file_container = (RelativeLayout) findViewById(R.id.rl_file_container);
        getIntentValue();
        if (StringUtils.isNullOrEmpty(pdfUrl)) {
            finish();
            return;
        }
        fileExtension = FileUtils.getFileType(pdfUrl);
        if ("pdf".equals(fileExtension) || "PDF".equals(fileExtension) ||
                "doc".equals(fileExtension) || "docx".equals(fileExtension)) {
            instance = OkGo.getInstance();
            tvItemWebError.setVisibility(View.VISIBLE);
            mTbsReaderView = new TbsReaderView(this, this);
            rl_file_container.addView(mTbsReaderView, new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT));
            String param = pdfUrl.split("\\?")[1];
            urlParam = processParam(param);
            fileName = urlParam.get("id").concat("." + fileExtension);
            downloadOrOpenFile();
        } else {
            tvItemWebError.setVisibility(View.GONE);
            browserLayout = new BrowserLayout(this);
            mWebView = browserLayout.getWebView();
            rl_file_container.addView(browserLayout, new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT));
            setWebViewConfig(pdfUrl);
        }

        if (!StringUtils.isNullOrEmpty(fundName) && !StringUtils.isNullOrEmpty(fundCode))
            cmtv_title.setText(fundName + " " + fundCode);
        subTitle.setText("公告详情");
        if (!TextUtils.isEmpty(getFundCustomerNo())) {
            queryAttentionByFundcode();
        }

        if (!TextUtils.isEmpty(fundCode)) {
            queryFundInfo(fundCode);
        }

        tvItemWebError.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ll_item_web_error.setVisibility(View.GONE);
                downloadOrOpenFile();
            }
        });
    }

    private void getIntentValue() {
        Intent intent = getIntent();
        pdfUrl = intent.getStringExtra("url");
        fundName = intent.getStringExtra("fundName");
        fundCode = intent.getStringExtra("fundCode");
        fundType = intent.getStringExtra("fundType");
        fileExtension = intent.getStringExtra("fileType");
    }

    private void downloadOrOpenFile() {
        if (PermissionManager.getInstance().checkPermissions(this,PermissionManager.PERMISSION_READ_WRITE)){
            File file = new File(DiskUtils.CACHE_PATH, fileName);
            long fileLength = PreferencesUtils.getLong(this, fileName);
            if (file != null && fileLength != -1 && file.length() == fileLength && file.exists() && file.isFile()) {
                //如果本地存在文件则直接打开否则去下载
                openPdfFile(file);
            } else {
                downloadFile();
            }
        } else {
            PermissionManager.getInstance().requestPermissions(this, PermissionManager.REQUEST_READ_WRITEE,
                    PermissionManager.PERMISSION_READ_WRITE, this);
        }
    }


    @Override
    public void onPermissionSuccess() {
        downloadOrOpenFile();
    }

    @Override
    public void onPermissionFail() {
        ToastUtils.showShort("获取权限失败");
        finish();
    }

    private Progress mProgress;

    private void downloadFile() {
        if (CommonUtil.isNetWorkConnected(this)) {
            instance.<File>get(pdfUrl)//
                    .tag(pdfUrl)//
                    .execute(new FileCallback(DiskUtils.CACHE_PATH, fileName) {

                        @Override
                        public void onStart(Request<File, ? extends Request> request) {
                            top_progress.setVisibility(View.VISIBLE);
                        }

                        @Override
                        public void onSuccess(Response<File> response) {
                            ll_item_web_error.setVisibility(View.GONE);
                            top_progress.setVisibility(View.GONE);
                            PreferencesUtils.putLong(SupperFileActivity.this, mProgress.fileName, mProgress.totalSize);
                            MentorLogger.Loge("文件大小" + mProgress.totalSize);
                            openPdfFile(response.body());
                        }

                        @Override
                        public void onError(Response<File> response) {
                            top_progress.setVisibility(View.GONE);
                            ll_item_web_error.setVisibility(View.VISIBLE);

                        }

                        @Override
                        public void downloadProgress(Progress progress) {
                            mProgress = progress;
                            top_progress.setCurProgress((int) (progress.fraction * 10000));
                        }
                    });
        }
    }

    private void openPdfFile(File file) {
        if (null != file) {
            displayFile(file);
        }
    }

    private void displayFile(File file) {
        if (file != null && !TextUtils.isEmpty(file.toString())) {
            //增加下面一句解决没有TbsReaderTemp文件夹存在导致加载文件失败
            String bsReaderTemp = "/storage/emulated/0/TbsReaderTemp";
            File bsReaderTempFile = new File(bsReaderTemp);

            if (!bsReaderTempFile.exists()) {
                boolean mkdir = bsReaderTempFile.mkdir();
                if (!mkdir) {
                }
            }
            Bundle bundle = new Bundle();
            bundle.putString("filePath", file.getPath());
            bundle.putString("tempPath", Environment.getExternalStorageDirectory() + "/" + "TbsReaderTemp");
            boolean result = mTbsReaderView.preOpen(fileExtension, false);
            if (result) {
                mTbsReaderView.openFile(bundle);
            }
        }
    }

    private String token = "";

    @Override
    protected void onResume() {
        super.onResume();
        if (!token.equals(getToken())) {
            token = getToken();
            if (!TextUtils.isEmpty(getFundCustomerNo())) {
                queryAttentionByFundcode();
            }
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }

    @OnClick({R.id.leftButton, R.id.rightButton, R.id.shareButton})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.leftButton:
                finish();
                break;
            case R.id.rightButton:
                if (!isFastDoubleClick()) {
                    if (mentorApplication.needLogin()) {
                        ActivityUtils.gotoLogin(mActivity, hasUser(), false, findUserId());
                    } else {
                        if (isFollow) {
                            attentionsCommand(0);
                        } else {
                            attentionsCommand(1);
                        }
                    }
                }
                break;
            case R.id.shareButton:
                if (!isFastDoubleClick()) {
                    //请求查询基金接口获取近一年收益值
                    String periodYearOne = getFundPeriodYearOne();

                    String url = HostConstant.HOST_WEB_URL_HEADER + String.format("fundDetailSec.html?fundCode=%s&fundType=%s", fundCode, fundType);
//                    SharePopup.Share(mActivity, mActivity.getResources().getString(R.string.share_title), url, fundName + " " +
//                            "" + fundCode + "\n近一年收益率" + periodYearOne);
                }
                break;
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        destoryAll();
    }

    /**
     * 查询某个基金是否被关注
     */
    private void queryAttentionByFundcode() {
        Map<String, String> params = new HashMap<>();
        params.put("fundCustomerNo", getFundCustomerNo());
        params.put("fundCode", fundCode);

        instance.<String>post(HostConstant.QUERY_ATTENTIONS_BY_FUNDCODE)
                .tag(this)
                .params(HttpUtils.getCommonParams(this, params))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        UpdateUI(response.body());
                    }


                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        showToast("网络加载失败，请稍后再试!");
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }
                });
    }


    private void UpdateUI(String resultJson) {

        QueryAttentionByFundcodeBean bean;

        try {
            bean = new Gson().fromJson(resultJson, QueryAttentionByFundcodeBean.class);
        } catch (Exception e) {
            Logger.e(TAG, "Gson解析数据时发生异常");
            e.printStackTrace();
            return;
        }

        if (!CommonUtil.checkState(mActivity, bean, resultJson)) {
            return;
        }

        if (bean.getData() == null) {
            showConfirmAlert(mActivity, "数据为空");
            return;
        }

        switch (bean.getData().getIsAttention()) {
            case 0:
                isFollow = false;
                rightButton.setBackgroundResource(R.mipmap.nav_like_white);
                break;
            case 1:
                isFollow = true;
                rightButton.setBackgroundResource(R.mipmap.nav_like_ac_white);
                break;
            default:
                break;
        }

    }

    /**
     * 取消/添加关注
     *
     * @param action 0为取消关注，１为添加关注
     */
    private void attentionsCommand(int action) {
        Map<String, String> params = new HashMap<>();

        params.put("fundCustomerNo", getFundCustomerNo());
        params.put("fundCode", fundCode);
        params.put("action", action + "");
        instance.<String>post(HostConstant.ATTENTIONS_COMMAND)
                .tag(this)
                .params(HttpUtils.getCommonParams(this, params))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        UpdateAttentionsCommand(response.body());
                    }


                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        showToast("网络加载失败，请稍后再试!");
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }
                });
    }

    private void UpdateAttentionsCommand(String json) {

        AttentionsCommandBean bean;
        try {
            bean = new Gson().fromJson(json, AttentionsCommandBean.class);
        } catch (Exception exception) {
            showConfirmAlert(mActivity, "提示", "数据解析错误");
            return;
        }

        if (!CommonUtil.checkState(mActivity, bean, json)) {
            return;
        }

        if (bean.isData()) {
            if (isFollow) {
                isFollow = false;
                rightButton.setBackgroundResource(R.mipmap.nav_like_white);
                showToast("取消关注成功");
            } else {
                isFollow = true;
                rightButton.setBackgroundResource(R.mipmap.nav_like_ac_white);
                showToast("添加关注成功");
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    private void destoryAll() {
        instance.cancelTag(pdfUrl);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        destoryAll();
        if (unbinder != null) {
            unbinder.unbind();
        }
        if (mTbsReaderView != null) {
            mTbsReaderView.onStop();
        }

        if (browserLayout != null) {
            browserLayout.destory();
        }
    }

    @Override
    public void onCallBackAction(Integer integer, Object o, Object o1) {
        MentorLogger.Loge("*******************integer=" + integer + ",o=" + o.toString() + ",o1=" + o1.toString());
    }


    public void setWebViewConfig(String url) {
        if (mWebView == null || StringUtils.isNullOrEmpty(url)) {
            MentorLogger.Loge("url不能为空 或者 webview不能为空");
            return;
        }
        // TODO: 2018/1/19 防止通过file域来恶意攻击
        mWebView.getSettings().setAllowFileAccess(false);
        if (url.startsWith("file://")) {
            mWebView.getSettings().setJavaScriptEnabled(false);
            mWebView.getSettings().setAllowFileAccessFromFileURLs(false);
            mWebView.getSettings().setAllowUniversalAccessFromFileURLs(false);
        } else {
            mWebView.getSettings().setJavaScriptEnabled(true);
        }
        mWebView.setWebViewClient(mWebViewClient);
        mWebView.setWebChromeClient(mWebChromeClient);
        if (url.startsWith("http")) {
            mWebView.loadUrl(url);
        } else {
            mWebView.loadDataWithBaseURL("about:blank", url, "text/html", "utf-8", null);
        }
        mWebView.removeJavascriptInterface("searchBoxJavaBridge_");
        mWebView.removeJavascriptInterface("accessibility");
        mWebView.removeJavascriptInterface("accessibiltyTraversal");
    }


    private WebViewClient mWebViewClient = new WebViewClient() {

        @Override
        public void onLoadResource(WebView view, String url) {
            MentorLogger.Loge(TAG, "onLoadResource " + view.getProgress());
            super.onLoadResource(view, url);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView webview, String url) {
            MentorLogger.Loge(TAG, "shouldOverrideUrlLoading url=" + url);
            webview.loadUrl(url);
            return true;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            String title = view.getTitle();
            if (!isLoadError) {
                browserLayout.setShowErrorView(false);
            } else {
                isLoadError = false;
                browserLayout.setShowErrorView(true);
            }

            if ("网页无法打开".equals(title) || title.contains("404")) {
                browserLayout.setShowErrorView(true);
            }
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            MentorLogger.Loge(TAG, "onReceivedError" + error.getErrorCode());
            isLoadError = true;
            browserLayout.setShowErrorView(true);
            super.onReceivedError(view, request, error);
        }

        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        @Override
        public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
            MentorLogger.Loge(TAG, "onReceivedHttpError" + errorResponse.getStatusCode());
            super.onReceivedHttpError(view, request, errorResponse);
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
//            handler.proceed();// 接受所有网站的证书  前两个是代表日期问题，第三个是webview的bug，最后一个是证书丢失，
            if (error.getPrimaryError() == SslError.SSL_DATE_INVALID
                    || error.getPrimaryError() == SslError.SSL_EXPIRED
                    || error.getPrimaryError() == SslError.SSL_INVALID
                    || error.getPrimaryError() == SslError.SSL_UNTRUSTED) {

                handler.proceed();

            } else {
                handler.cancel();
            }
            MentorLogger.Loge(TAG, "onReceivedSslError" + error.getUrl());
        }
    };


    private WebChromeClient mWebChromeClient = new WebChromeClient() {

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
            MentorLogger.Loge(TAG, "onProgressChanged:" + newProgress);
            browserLayout.setCurProgress(newProgress);
        }

        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
            MentorLogger.Loge(TAG, "onJsAlert:" + message);
            result.confirm();
            return true;
        }

        @Override
        public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {
            MentorLogger.Loge(TAG, "onJsConfirm:" + message);
            return super.onJsConfirm(view, url, message, result);
        }

        @Override
        public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {
            MentorLogger.Loge(TAG, "onJsPrompt:" + url);
            return super.onJsPrompt(view, url, message, defaultValue, result);
        }
    };

}
